import {H2oMoment } from "./bo"
import { H2oMethod } from "./constant"
import { getTid,getTime } from "./functions"
import { dao } from "./repository"

var httpHost = "https://askdao.top"
export function DoLogin(code:string, name:string, avator:string,
                        ok:(res:any)=>void,
                        reject:(res:any)=>void){
    const api = `${httpHost}/h2o/api/v1/user/wxlogin`
    const body = {"tid":getTid(), "time":getTime(),"wxcode":code,"nickname":name, "avatar":avator}
    doPost(api, body, (res:any)=>{
        dao.login(name, avator, res.header.Authorization, res.header.Xh2orole)
        ok(res)}, 
        (res:any)=>{reject(res)})
}

export function DoCreateMoment(moment:H2oMoment, ok:(res:any)=>void, fail:(res:any)=>void){
  const api = `${httpHost}/h2o/oss/upload?tag=moment`
  const data = new Map<string,string>();
  data.set("Tags", H2oMethod.Moment)
  doUpload(api, moment.img, data,(res:any)=>{
    moment.img = res.data
    const url = `${httpHost}/h2o/api/v1/moment/publish`
    doPost(url, moment, (res:any)=>{ok(res)}, (res:any)=>{fail(res)})
  },(res:any)=>{fail(res)})
}

export function QRecommendHot(page: number, pageSize:number, cb:(data:any)=>void){
  const api = `${httpHost}/h2o/api/v1/moment/recommend?page=${page}&pageSize=${pageSize}`
  doGet(api, cb)
}

export function DoUploadAvator(avator:string) {
  const api = `${httpHost}/h2o/api/v1/user/wxupload-avator`
  doUpload(api, avator, new Map<string,string>(), (_res:any)=>{}, (_res:any)=>{})
}

export function DoUpdateMoment(body:any){
  const api = `${httpHost}/h2o/api/v1/moment/update`
  doPost(api, body, (_:any)=>{}, (_:any)=>{})
}

function doGet(url:string, cb:(data:any)=>void){
  wx.request({
    url: url,
    method:"GET",
    header: {'content-type': 'application/json'},
    success: (res:any)=>{
      if ((res.statusCode === 200) && (res.data.code === 200)){
        cb(res.data.data)
      }
    },
    fail: (_res:any)=>{}
  })  
}

function doUpload(url:string,name:string,data:Map<string,string>, ok:(res:any)=>void, fail:(res:any)=>void){
  const jwt = dao.getJwt()
  wx.uploadFile({
    url: url, 
    filePath: name, 
    name: 'file',
    formData:data,
    header:{'Authorization': jwt,'content-type':'multipart/form-data'},
    success (_res){
      const {statusCode} = _res 
      if(statusCode === 200){
        ok(_res)
      }else{
        fail(_res)
      }
    },
    fail(_res){fail(_res)}
  })
}

function doPost(url:string, body:any, ok:(res:any)=>void, fail:(res:any)=>void){
  const jwt = dao.getJwt()
  if(jwt === ""){
    return 
  }
  wx.request({
    url: url,
    method:"POST",
    header: {'Authorization': jwt, 'content-type': 'application/json'},
    data:body,
    success: (res:any)=>{
      if (res.statusCode === 200){
        ok(res)
      }else{
        if(res.statusCode === 401){

        } 
        fail(res)
      }
    },
    fail: (res:any)=>{fail(res)}
  })  
}